<template>
  <div>
    <el-dialog v-model="dialogFormVisible" title="编辑商铺">
      <el-form :model="form">
        <el-form-item label="商铺名称" label-width="140px">
          <el-input v-model="form.shopName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="商铺介绍" label-width="140px">
          <el-input v-model="form.shopIntroduce" autocomplete="off" type="textarea" />
        </el-form-item>

        <el-form-item label="商铺位置" label-width="140px">
          <el-input v-model="form.shopAddress" autocomplete="off" type="textarea" />
        </el-form-item>

        <el-form-item label="状态" label-width="140px">
          <el-select-v2
            v-model="form.state"
            :options="optionList"
            placeholder="请选择店铺状态"
          />
        </el-form-item>

        <el-form-item label="店铺主" label-width="140px">
          <el-select-v2
            v-model="form.userId"
            :options="UserList"
            placeholder="请选择店铺主"
          />
        </el-form-item>

        <el-form-item label="图片" label-width="140px">
          <el-upload
            v-model:file-list="form.shopImg"
            action="/api/upload/img"
            :headers="tokenBody"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="hanleSuccess"
            limit="1"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <el-dialog v-model="photoShowFlag">
        <img :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="Edit"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="新增商铺" v-model="ShopDialogFormVisible">
      <el-form :model="insert" :rules="Irules">
        <el-form-item label="店铺名称" label-width="140px">
          <el-input v-model="insert.shopName" placeholder="请输入店铺名称"></el-input>
        </el-form-item>

        <el-form-item label="店铺主" label-width="140px">
          <el-select-v2
            v-model="insert.userId"
            placeholder="请选择店铺主"
            :options="UserList"
          />
        </el-form-item>
        <el-form-item label="店铺简介" label-width="140px">
          <el-input
            v-model="insert.shopIntroduce"
            placeholder="请输入店铺简介"
            type="textarea"
          ></el-input>
        </el-form-item>

        <el-form-item label="店铺地址" label-width="140px">
          <el-input v-model="insert.shopAddress" placeholder="请输入店铺地址"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="ShopDialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="insertAll"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/manager/index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/manager/shop">店铺信息</a></el-breadcrumb-item>
    </el-breadcrumb>
    <div class="header">
      <div style="width: 200px">
        <el-input v-model="input" placeholder="请输入搜索内容" />
      </div>
      <el-button type="primary" @click="search" style="margin-left: 10px">搜索</el-button>
      <el-button type="primary" @click="reactSearch">重置</el-button>
    </div>
    <div class="insert">
      <el-button type="info" size="large" @click="ChooseIF" style="margin-right: 50px"
        >新增商铺</el-button
      >
    </div>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column label="商铺名称">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <el-icon><timer /></el-icon>
            <span style="margin-left: 10px">{{ scope.row.shopName }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="简介" prop="shopIntroduce" width="300px" />

      <el-table-column label="图片" width="120px">
        <template #default="scope">
          <!-- <div class="demo-image__preview">
            <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.shopImg"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :initial-index="4"
              fit="cover"
            />
          </div> -->

          <div class="demo-image__preview">
            <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.shopImg"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="scope.row.shopImg"
              :initial-index="4"
              fit="cover"
            />
          </div>
        </template>
      </el-table-column>

      <el-table-column label="入驻时间" prop="inputTime" width="200px"></el-table-column>
      <el-table-column label="状态" width="100px">
        <template #default="scope">
          <div>{{ scope.row.state == "1" ? "正常" : "关闭" }}</div>
        </template>
      </el-table-column>

      <el-table-column label="Operations">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageSize"
      v-model:page-size="pageItem"
      :page-sizes="[20, 30, 50, 100]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="ItemTotal"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script lang="ts" setup>
import axios from "axios";
import { ref, reactive } from "vue";
import { Timer, Message } from "@element-plus/icons-vue";
import { el } from "element-plus/es/locale";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, Download, Plus, ZoomIn } from "@element-plus/icons-vue";
import type { UploadFile } from "element-plus";
import type { UploadProps, UploadUserFile } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

const token = ref(localStorage.getItem("admin_token"));

const optionList = ref([
  {
    label: "正常",
    value: "1",
  },
  {
    label: "关闭",
    value: "0",
  },
]);

const UserList = ref([]);

const ShopDialogFormVisible = ref(false);

const tokenBody = {
  token: token.value,
};

const Edit = () => {
  const req = {
    shopId: form.shopId,
    shopName: form.shopName,
    shopImg: form.img,
    shopAddress: form.shopAddress,
    shopIntroduce: form.shopIntroduce,
    state: form.state,
    userId: form.userId,
  };
  axios
    .post("/api/shop/update", req, {
      headers: {
        token: token.value,
      },
    })
    .then((res) => {
      // console.log(res);
      if (res.data.success) {
        ElMessage({
          message: "更新成功",
          type: "success",
        });
      } else {
        ElMessage({
          message: "更新失败",
          type: "error",
        });
      }
    })
    .catch((err) => {
      console.log(err);
    });
  setTimeout(() => {
    search();
    dialogFormVisible.value = false;
  }, 200);
};

// const fileList = ref<UploadUserFile[]>([]);

const dialogFormVisible = ref(false);
const photoShowFlag = ref(false);
const dialogImageUrl = ref("");

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const hanleSuccess: UploadProps["onSuccess"] = (res) => {
  // console.log(res);
  // form.img.push({
  //   name: res.message,
  //   url: res.message,
  // });
  // console.log("form.shopImg :", form.shopImg);
  form.shopImg = <UploadUserFile[]>[];
  form.img = res.message;
  form.shopImg.push({
    name: res.message,
    url: res.message,
  });
  console.log(JSON.stringify(form.shopImg));
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  photoShowFlag.value = true;
};

interface Shop {
  shopId: string;
  inputTime: Date;
  updateTime: Date;
  state: number;
  shopName: string;
  shopAddress: string;
  userId: string;
  shopIntroduce: string;
}
const insert = reactive<insertI>({
  shopName: "",
  shopAddress: "",
  userId: "",
  shopIntroduce: "",
});

interface insertI {
  shopName: string;
  shopAddress: string;
  userId: string;
  shopIntroduce: string;
}

const Irules = reactive<FormRules<insertI>>({
  shopName: [
    { required: true, message: "Please input shopName", trigger: "blur" },
    { min: 4, max: 40, message: "Length should be 4 to 40", trigger: "blur" },
  ],
  shopAddress: [
    { required: true, message: "Please input shopAddress", trigger: "blur" },
    { min: 4, max: 100, message: "Length should be 4 to 100", trigger: "blur" },
  ],
  shopIntroduce: [
    { required: true, message: "Please input shopIntroduce", trigger: "blur" },
    { min: 4, max: 254, message: "Length should be 4 to 254", trigger: "blur" },
  ],
  userId: [{ required: true, message: "Please choose user", trigger: "blur" }],
});

const insertAll = () => {
  const req = {
    shopName: insert.shopName,
    shopIntroduce: insert.shopIntroduce,
    userId: insert.userId,
    shopAddress: insert.shopAddress,
  };
  axios
    .post("/api/shop/insert", req, {
      headers: {
        token: token.value,
      },
    })
    .then((res) => {
      // console.log(res);
      if (res.data.success) {
        ElMessage({
          type: "success",
          message: "新建成功",
        });
      } else {
        ElMessage({
          type: "error",
          message: res.data.message,
        });
      }
    })
    .catch((err) => {
      console.log(err);
    });
  setTimeout(() => {
    insert.shopName = "";
    insert.userId = "";
    insert.shopIntroduce = "";
    insert.shopAddress = "";
    ShopDialogFormVisible.value = false;
    search();
  }, 200);
};
/**
 * 用于表格的数据展示
 * */
const form = reactive({
  shopId: "",
  inputTime: new Date(),
  updateTime: new Date(),
  state: 1,
  shopName: "",
  shopAddress: "",
  userId: "",
  shopIntroduce: "",
  shopImg: <UploadUserFile[]>[],
  img: "",
  businessStartTime: "",
  businessEndTime: "",
});
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  search();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  search();
};

const handleEdit = (index: number, row: Shop) => {
  form.shopId = row.shopId;
  form.shopName = "";
  form.shopIntroduce = "";
  form.shopImg = <UploadUserFile[]>[];
  form.userId = "";
  axios
    .get("/api/shop/get/" + row.shopId, {
      headers: {
        token: token.value,
      },
    })
    .then((res) => {
      // console.log(res);
      const msg = res.data.message;
      form.userId = msg.userId;
      form.shopName = msg.shopName;
      form.shopAddress = msg.shopAddress;
      form.shopIntroduce = msg.shopIntroduce;
      form.state = msg.state;
      if (msg.shopImg != "" && msg.shopImg != undefined) {
        form.shopImg.push({
          name: msg.shopImg,
          url: msg.shopImg,
        });
        form.img = msg.shopImg;
      }
    })
    .catch((err) => {
      console.log(err);
    });
  setTimeout(() => {
    getUserInfo();
    dialogFormVisible.value = true;
    console.log(index, row);
  }, 300);
};
const handleDelete = (index: number, row: Shop) => {
  console.log(index, row);
  console.log(row);

  ElMessageBox.confirm("是否删除该商品" + row.shopName, "警告", {
    confirmButtonText: "确认删除",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      axios
        .get("/api/shop/Rdel?shopId=" + row.shopId, {
          headers: {
            token: token.value,
          },
        })
        .then((res) => {
          // console.log(res);
          if (res.data.success) {
            ElMessage({
              type: "success",
              message: "删除成功",
            });
          } else {
            ElMessage({
              type: "error",
              message: res.data.message,
            });
          }
          search();
        })
        .catch((err) => {
          console.log(err);
        });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

const tableData = ref([]);

const input = ref("");
const pageSize = ref(1);
const pageItem = ref(20);
const PageTotal = ref(0);
const ItemTotal = ref(0);

const reactSearch = () => {
  pageSize.value = 1;
  pageItem.value = 20;
  input.value = "";
  setTimeout(() => {
    search();
  }, 200);
};

const search = () => {
  axios
    .get(
      "/api/shop/admin/select/" +
        pageSize.value +
        "/" +
        pageItem.value +
        "?shopName=" +
        input.value,
      {
        headers: {
          token: token.value,
        },
      }
    )
    .then((res) => {
      console.log(res);
      const msg = res.data.message.list;
      console.log(msg);
      tableData.value = msg;
      console.log(tableData.value);
      PageTotal.value = res.data.message.pages;
      ItemTotal.value = res.data.message.total;
    })
    .catch((err) => {
      console.log(err);
    });
};
const ChooseIF = () => {
  getUserInfo();
  ShopDialogFormVisible.value = true;
};
const getUserInfo = () => {
  axios
    .get("/api/auth/user/list", {
      headers: {
        token: token.value,
      },
    })
    .then((res) => {
      console.log(res);
      UserList.value = res.data.message;
      console.log("UserList.value :", UserList.value);
    })
    .catch((err) => {});
};

search();
</script>

<style lang="scss" scoped>
.header {
  height: 50px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.insert {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}
.demo-image__error .image-slot {
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}
</style>
